package net.jacqeush.mini.rpc.annotation.auto.register;

import lombok.SneakyThrows;
import net.jacqeush.mini.rpc.annotation.RpcService;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;

/**
 * @author Jacquesh
 * @version 1.0
 * @date 2020/10/21 20:06
 */
public class RpcBeanNameGenerator implements BeanNameGenerator{
  private  ClassLoader classLoader=this.getClass().getClassLoader();
    @SneakyThrows
    @Override
    public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {

          String clazzPath= definition.getBeanClassName();
          Class<?> clazz=   classLoader.loadClass(clazzPath);

         if(clazz.getAnnotation(RpcService.class)!=null){
             String beanName=clazz.getAnnotation(RpcService.class).value();
             if (StringUtils.isNotBlank(clazz.getAnnotation(RpcService.class).value())){
                 return beanName;
             }else{
                 return BeanDefinitionReaderUtils.generateBeanName(definition, registry);
             }
         }else {
             return BeanDefinitionReaderUtils.generateBeanName(definition, registry);
         }

    }


}
